package handler.accountFormHandlers;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.JOptionPane;

import other.CodeDescriptionPair;

import checker.AddAssetFormChecker;

import db.Account;
import db.DBConnectionFactory;
import db.DBConnector;
import form.AccountForm.AccountForm;

public class ManageAccountSaveButtonActionListener implements ActionListener {

	AccountForm accountForm;
    DBConnector db;
	
	public ManageAccountSaveButtonActionListener(AccountForm accountForm){
		this.accountForm = accountForm;
		db = new DBConnector();
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		Account oldAccount = Account.createAccount(accountForm.getUserName().getInput());
		Account newAccount = oldAccount.getCopy();
		newAccount.setAcctTypeCode(getCode(accountForm.getAcctType().getInput()));
		newAccount.updateSelfinDB(newAccount);
	}
	
	private String getCode(String acctTypeDesc){
		String newAcctType = null;
		
		String query = "SELECT code FROM usertypes WHERE description = '" + acctTypeDesc +"';";
		Connection con = DBConnectionFactory.getInstance().getConnection();
		ResultSet rs = DBConnector.executeQuery(con, query);

		try {
			while(rs.next())
				newAcctType = rs.getString("code");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	
		
		try {
			con.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return newAcctType;
	}
}
